package com.unisedu.oa.service;

import com.unisedu.oa.Entity.EmployeeEntity;
import com.unisedu.oa.mapper.EmployeeMapper;
import com.unisedu.oa.utils.JwtUtils;
import com.unisedu.oa.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class EmployeeService extends BaseService<EmployeeMapper, EmployeeEntity> {

    @Value("${config.secret}")
    private String secret;


    /**
     * 获取缓存中的用户对象
     * @param request
     * @return
     */
    public EmployeeEntity get(HttpServletRequest request) {
        String employeeId = request.getAttribute("employeeId").toString();
        EmployeeEntity employee = (EmployeeEntity)redisTools.getObject("EMPLOYEE_"+employeeId);
        return employee;
    }

    /**
     * 用户登录校验
     * @param request http请求
     * @return 返回登录结果
     */
    public String login(HttpServletRequest request){
        //获取用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //根据用户名获取用户对象
        EmployeeEntity employee = new EmployeeEntity();
        employee.setLoginName(username);
        employee = super.get(employee);

        //校验用户是否存在
        if(employee!=null){
            //校验用户密码是否正确
            if(employee.getPassword().equals(MD5Utils.MD5Encode(password))){
                //根据用户名生成token
                String token = "Bearer;"+JwtUtils.createJWT(username,employee.getId(), secret);
                //缓存用户
                redisTools.setObject("EMPLOYEE_"+employee.getId(), employee);

                return formatResult(200,null,token);
            }else{
                return formatResult(403, "用户名或密码错误" , null);
            }
        } else{
            return formatResult(404, "用户不存在", null);
        }
    }

}
